
let string = 'hello'
let num = 7
let takes = [
  'FORWARD 2',
  'BACKWARD 1',
  'SEARCH-FORWARD o',
  'SEARCH-BACKWARD h',
  'INSERT xx',
  'REPLACE xx',
  'DELETE x',
]
let index = 0
while ((take = takes.shift())) {
  let [action, handle] = take.split(' ')
  switch (action) {
    case 'FORWARD':
      index += +handle
      if (index > string.length) index = string.length
      break
    case 'BACKWARD':
      index -= +handle
      if (index < 0) index = 0
      break
    case 'SEARCH-FORWARD': {
      let substring = string.substring(0, index)
      if (substring.indexOf(handle) > -1) {
        index = substring.indexOf(handle)
      }
      break
    }

    case 'SEARCH-BACKWARD': {
      let substring = string.substring(index)
      if (substring.indexOf(handle) > -1) {
        index = substring.indexOf(handle) + index
      }
      break
    }

    case 'INSERT': {
      let arr = string.split('')
      arr.splice(index, 0, ...handle)

      string = arr.join('')
      index += handle.length
      break
    }
    case 'REPLACE': {
      let len = handle.length
      let arr = string.split('')
      arr.splice(index, len, ...handle)
      string = arr.join('')
    //   index += len
      break
    }

    case 'DELETE': {
      let arr = string.split('')
      arr.splice(index - Number(handle), index, '')
      string = arr.join('')
      index -= +handle
      break
    }
  }
}

console.log(string)
